package com.qf.ssm.utlis;

import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class ImageUtils {
    private static String KEY = "bdb40f2727781dbdeef7e51108685879";
    public static String GD_URL="https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";
    private static String SUCCESS_FLAG="1";
    private static final String AMAP_STATIC_MAP_URL = "https://restapi.amap.com/v3/staticmap";

    public static String getImage(String address){
        String[] locations = getLonAndLatByAddress(address).split(",");
        String fileName = "Image.png";
        // 设置经纬度坐标
        double longitude =Double.parseDouble(locations[0].trim());
        double latitude = Double.parseDouble(locations[1].trim());
        // 构造静态地图的请求 URL
        String staticMapUrl = buildStaticMapUrl(longitude, latitude);
        // 发送 HTTP 请求，获取静态地图图片
        try {
            InputStream inputStream = sendHttpRequest(staticMapUrl);
            saveToFile(inputStream, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }


    //拼接URL
    private static String buildStaticMapUrl(double longitude, double latitude) {
        String markers = "large,,A:"+longitude+","+latitude;
        String paths = "10,,1,0xffa500,0.5:"+longitude+","+latitude;
        return String.format("%s?location=%f,%f&size=750*500&zoom=13&%s&markers=%s&key=%s",AMAP_STATIC_MAP_URL,longitude,latitude,paths,markers,KEY);
    }

    //发送http请求
    private static InputStream sendHttpRequest(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            return connection.getInputStream();
        } else {
            throw new RuntimeException("HTTP request failed. Response Code: " + responseCode);
        }
    }

    //保存文件
    private static void saveToFile(InputStream inputStream, String fileName){
        try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String getLonAndLatByAddress(String address){
        String location = "";
        GD_URL = String.format(GD_URL,address,KEY);
        //
        String queryResult = getResponse(GD_URL);
        JSONObject obj = JSONObject.parseObject(queryResult);
        if (String.valueOf(obj.get("status")).equals(SUCCESS_FLAG)){
            JSONObject jobJSON = JSONObject.parseObject(obj.get("geocodes").toString().substring(1,obj.get("geocodes").toString().length()-1));
            location = String.valueOf(jobJSON.get("location"));
        }else {
            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
        }
        return location;
    }
    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(result);
        return result.toString();
    }
}
